package org.transformatorhuis.unix.server.example;

import java.io.Serializable;
import java.util.Observable;
import java.util.Observer;

/**
 * User: Olivier Van Acker
 * Date: Mar 25, 2010
 */
public class ExampleSerializableThread implements Runnable, Observer, Serializable {

    private boolean shutdown = false;
    private String identifier;

    public ExampleSerializableThread(String identifier) {
        this.identifier = identifier;
    }

    private void sendMessage() {
        System.out.println(identifier + "::Message from server");
    }

    @Override
    public void run() {
        while(!shutdown) {
            sendMessage();
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                System.err.println("Thread interrupted: " + e.toString());
                System.exit(0);
            }
        }
        System.out.println(identifier+"::End of thread");
    }

    @Override
    public void update(Observable o, Object arg) {
        System.out.println(identifier + "::TERM received");
        shutdown = true;    
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        ExampleSerializableThread that = (ExampleSerializableThread) o;

        if (shutdown != that.shutdown) return false;
        if (identifier != null ? !identifier.equals(that.identifier) : that.identifier != null) return false;

        return true;
    }

    @Override
    public int hashCode() {
        int result = (shutdown ? 1 : 0);
        result = 31 * result + (identifier != null ? identifier.hashCode() : 0);
        return result;
    }
}
